import { Entity } from '../systems/EntitySystem.js';
import { RenderSystem } from '../systems/RenderSystem.js';
import { GameConfig, DefenseSystemType } from '../config/GameConfig.js';
import { Missile } from './Missile.js';

export class Interceptor implements Entity {
    public id: string;
    public x: number;
    public y: number;
    public width: number = 8;
    public height: number = 16;
    public active: boolean = true;
    public target: Missile; // 🔧 将target改为public，便于外部访问
    
    private systemType: DefenseSystemType;
    private velocity: { x: number; y: number } = { x: 0, y: 0 };
    private speed: number = 0;
    private accuracy: number;
    private flightTime: number = 0;
    private maxFlightTime: number = 3000;
    private lastRenderLog: number = 0; // 🔍 用于控制渲染日志输出频率
    
    // 🚀 新增：记录发射源位置，用于更好的尾迹效果
    private launchX: number;
    private launchY: number;
    private flightPath: Array<{ x: number; y: number; timestamp: number }> = [];

    constructor(id: string, systemType: DefenseSystemType, startX: number, startY: number, target: Missile, accuracy: number) {
        this.id = id;
        this.systemType = systemType;
        this.x = startX;
        this.y = startY;
        this.target = target;
        this.accuracy = accuracy;
        
        // 🚀 记录发射源位置
        this.launchX = startX;
        this.launchY = startY;
        
        // 设置拦截弹参数
        if (systemType === 'IRON_DOME') {
            this.speed = 500;
            this.maxFlightTime = 3000;
        } else if (systemType === 'ARROW_3') {
            this.speed = 400;
            this.maxFlightTime = 5000;
        } else {
            this.speed = 300;
            this.maxFlightTime = 4000;
        }
        
        // 计算初始速度方向
        this.calculateInitialVelocity();
        
        // 🚀 强制日志确认创建
        console.log(`🚀🚀🚀 拦截弹创建成功!`);
        console.log(`   ID: ${this.id}`);
        console.log(`   类型: ${this.systemType}`);
        console.log(`   起始位置: (${this.x.toFixed(0)}, ${this.y.toFixed(0)})`);
        console.log(`   发射源: (${this.launchX.toFixed(0)}, ${this.launchY.toFixed(0)})`);
        console.log(`   目标: ${this.target.id} @ (${this.target.x.toFixed(0)}, ${this.target.y.toFixed(0)})`);
        console.log(`   速度: ${this.speed}px/s`);
        console.log(`   精度: ${this.accuracy}%`);
        console.log(`   初始速度向量: (${this.velocity.x.toFixed(2)}, ${this.velocity.y.toFixed(2)})`);
    }

    private calculateInitialVelocity(): void {
        // 预测目标位置
        const targetPos = this.predictTargetPosition();
        
        const dx = targetPos.x - this.x;
        const dy = targetPos.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        this.velocity = {
            x: (dx / distance) * this.speed,
            y: (dy / distance) * this.speed
        };
    }

    private predictTargetPosition(): { x: number; y: number } {
        // 简单的目标位置预测
        const timeToIntercept = 1.0;
        const targetVel = this.target.getVelocity();
        
        return {
            x: this.target.x + targetVel.x * timeToIntercept / 60,
            y: this.target.y + targetVel.y * timeToIntercept / 60
        };
    }

    update(deltaTime: number): void {
        if (!this.active) return;

        this.flightTime += deltaTime;
        
        // 更新位置
        this.x += this.velocity.x * deltaTime / 1000;
        this.y += this.velocity.y * deltaTime / 1000;
        
        // 🚀 记录飞行路径（用于增强尾迹效果）
        const now = Date.now();
        this.flightPath.push({ x: this.x, y: this.y, timestamp: now });
        
        // 保持路径长度合理（只保留最近1秒的路径）
        const cutoffTime = now - 1000;
        this.flightPath = this.flightPath.filter(point => point.timestamp > cutoffTime);
        
        // 检查碰撞
        this.checkCollision();
        
        // 检查飞行时间
        if (this.flightTime >= this.maxFlightTime) {
            this.explode(false);
        }
        
        // 检查边界
        if (this.x < 0 || this.x > GameConfig.CANVAS_WIDTH || 
            this.y < 0 || this.y > GameConfig.CANVAS_HEIGHT) {
            this.active = false;
        }
    }

    private checkCollision(): void {
        if (!this.target.active) {
            this.active = false;
            return;
        }
        
        const dx = this.x - this.target.x;
        const dy = this.y - this.target.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 碰撞检测距离50px
        if (distance < 50) {
            const hitChance = Math.random() * 100;
            if (hitChance < this.accuracy) {
                // 命中
                console.log(`🎯 拦截成功! ${this.id} 击中 ${this.target.id}`);
                this.createInterceptionExplosion(this.x, this.y);
                this.target.takeDamage(100);
                this.explode(true);
            } else {
                // 未命中
                console.log(`❌ 拦截失败! ${this.id} 未命中 ${this.target.id}`);
                this.explode(false);
            }
        }
    }
    
    private createInterceptionExplosion(x: number, y: number): void {
        // 触发视觉效果
        const visualEffectsSystem = (globalThis as any).gameEngine?.visualEffectsSystem;
        if (visualEffectsSystem) {
            visualEffectsSystem.createInterceptExplosion(x, y);
        }
        
        // 播放音效
        const audioSystem = (globalThis as any).gameEngine?.audioSystem;
        if (audioSystem) {
            audioSystem.playIntercept();
        }
    }

    private explode(hit: boolean): void {
        this.active = false;
        
        // 从EntitySystem中移除
        const entitySystem = (globalThis as any).gameEngine?.entitySystem;
        if (entitySystem) {
            entitySystem.removeEntity(this.id);
        }
    }

    render(renderSystem: RenderSystem): void {
        if (!this.active) return;
        
        // 🚀🚀🚀 每秒输出一次渲染确认（避免刷屏）
        const now = Date.now();
        if (!this.lastRenderLog || now - this.lastRenderLog > 1000) {
            console.log(`🎯 拦截器 ${this.id} 正在渲染! 位置: (${this.x.toFixed(1)}, ${this.y.toFixed(1)})`);
            this.lastRenderLog = now;
        }
        
        const color = this.getInterceptorColor();
        const ctx = (renderSystem as any).ctx;
        
        // 🔥 增强的尾迹效果 - 连接到发射源
        this.renderEnhancedTrail(renderSystem, color);
        
        // 🔥 主体 - 超大明亮导弹形状
        this.renderMissileBody(renderSystem, color);
        
        // 🔥 强制显示标识和连接线
        this.renderIdentificationMarkers(renderSystem);
        
        // 🔥 显示飞行路径（调试模式）
        if (GameConfig.DEBUG.ENABLED) {
            this.renderFlightPath(renderSystem);
        }
    }

    private renderEnhancedTrail(renderSystem: RenderSystem, color: string): void {
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        
        // 1. 从发射源到当前位置的连接线
        const gradient = ctx.createLinearGradient(this.launchX, this.launchY, this.x, this.y);
        gradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)'); // 发射源白色
        gradient.addColorStop(0.3, color); // 系统颜色
        gradient.addColorStop(1, 'rgba(255, 255, 255, 0.2)'); // 当前位置淡化
        
        ctx.strokeStyle = gradient;
        ctx.lineWidth = 8;
        ctx.lineCap = 'round';
        ctx.beginPath();
        ctx.moveTo(this.launchX, this.launchY);
        ctx.lineTo(this.x, this.y);
        ctx.stroke();
        
        // 2. 飞行路径尾迹
        if (this.flightPath.length > 1) {
            const maxAge = 1000; // 1秒
            const currentTime = Date.now();
            
            for (let i = 1; i < this.flightPath.length; i++) {
                const current = this.flightPath[i];
                const previous = this.flightPath[i - 1];
                const age = currentTime - current.timestamp;
                const alpha = Math.max(0, 1 - (age / maxAge));
                
                ctx.strokeStyle = `rgba(255, 255, 255, ${alpha * 0.8})`;
                ctx.lineWidth = 4 * alpha;
                ctx.beginPath();
                ctx.moveTo(previous.x, previous.y);
                ctx.lineTo(current.x, current.y);
                ctx.stroke();
            }
        }
        
        ctx.restore();
    }

    private renderMissileBody(renderSystem: RenderSystem, color: string): void {
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        
        // 计算导弹朝向
        const angle = Math.atan2(this.velocity.y, this.velocity.x);
        const length = 20;
        const width = 8;
        
        ctx.translate(this.x, this.y);
        ctx.rotate(angle);
        
        // 导弹主体
        ctx.fillStyle = color;
        ctx.fillRect(-length/2, -width/2, length, width);
        
        // 导弹头部
        ctx.fillStyle = 'white';
        ctx.beginPath();
        ctx.moveTo(length/2, 0);
        ctx.lineTo(length/2 - 6, -width/2);
        ctx.lineTo(length/2 - 6, width/2);
        ctx.closePath();
        ctx.fill();
        
        // 引擎火焰
        const flameLength = 15;
        ctx.fillStyle = 'rgba(255, 100, 0, 0.8)';
        ctx.beginPath();
        ctx.moveTo(-length/2, -width/4);
        ctx.lineTo(-length/2 - flameLength, 0);
        ctx.lineTo(-length/2, width/4);
        ctx.closePath();
        ctx.fill();
        
        ctx.restore();
        
        // 外围光环
        renderSystem.renderCircleEntity(this.x, this.y, 12, `rgba(255, 255, 255, 0.3)`);
        renderSystem.renderCircleEntity(this.x, this.y, 8, `${color}80`);
    }

    private renderIdentificationMarkers(renderSystem: RenderSystem): void {
        // 强制显示标识
        renderSystem.renderText(
            '🚀INTERCEPT',
            this.x - 35,
            this.y - 30,
            'white',
            'bold 12px Arial'
        );
        
        // 系统类型标识
        const systemLabel = this.systemType === 'IRON_DOME' ? 'IRON-DOME' : 
                           this.systemType === 'ARROW_3' ? 'ARROW-3' : 'DEFENSE';
        renderSystem.renderText(
            systemLabel,
            this.x - 25,
            this.y + 25,
            this.getInterceptorColor(),
            'bold 10px Arial'
        );
        
        // 位置信息
        renderSystem.renderText(
            `(${this.x.toFixed(0)},${this.y.toFixed(0)})`,
            this.x - 20,
            this.y + 40,
            'cyan',
            'bold 9px Arial'
        );
        
        // 发射源连接指示
        renderSystem.renderText(
            `FROM: (${this.launchX.toFixed(0)},${this.launchY.toFixed(0)})`,
            this.x - 40,
            this.y - 45,
            'yellow',
            'bold 8px Arial'
        );
    }

    private renderFlightPath(renderSystem: RenderSystem): void {
        const ctx = (renderSystem as any).ctx;
        ctx.save();
        
        // 渲染完整飞行路径点
        this.flightPath.forEach((point, index) => {
            const age = Date.now() - point.timestamp;
            const alpha = Math.max(0, 1 - (age / 1000));
            
            ctx.fillStyle = `rgba(0, 255, 255, ${alpha * 0.5})`;
            ctx.beginPath();
            ctx.arc(point.x, point.y, 2, 0, Math.PI * 2);
            ctx.fill();
        });
        
        ctx.restore();
    }

    private getInterceptorColor(): string {
        switch (this.systemType) {
            case 'IRON_DOME':
                return '#00FF00'; // 绿色
            case 'ARROW_3':
                return '#0080FF'; // 蓝色
            default:
                return '#FFFFFF'; // 白色
        }
    }

    public destroy(): void {
        this.active = false;
    }
}
